﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using System.Xml.Serialization;
using Kristall.Engine;
using Kristall.Engine.Scripts;

namespace Kristall.MyGame.Scripts
{
    public class DisappearScript : Script
    {
        public float Timer { get; set; }
        public float TriggerTime { get; set; }
        public float FadeDuration { get; set; }

        public bool TriggerOnPlayerCollission { get; set; }
        public bool TriggerOnce { get; set; }

        [XmlIgnore]        
        bool update = false;

        [XmlIgnore]
        AABB _aabb;

        [XmlIgnore]
        bool _triggered;

        float fadeTimer = 0;

        public DisappearScript() : base()
        {
            Timer = 0;
            TriggerTime = 1.0f;
            TriggerOnce = true;
            TriggerOnPlayerCollission = false;
            _triggered = false;
            FadeDuration = 0.5f;
            fadeTimer = FadeDuration;
        }

        public override void Load(Level level, AABB aabb)
        {
            _aabb = aabb;
            aabb.OnCollision += new EventHandler<CollisionEventArgs>(aabb_OnCollision);
        }

        void aabb_OnCollision(object sender, CollisionEventArgs e)
        {
            if (!(e.Other is Player))
                return;

            update = true;

            /*while (Timer > TriggerTime)
            {
                Timer -= TriggerTime;
            }*/
        }

        public override void Update(float dt)
        {
            if (!Enabled)
                return;

            fadeTimer = MathHelper.Clamp(fadeTimer + dt, 0, FadeDuration);

            if (_aabb is Animatable)
            {
                Animatable anim = (Animatable)_aabb;
                Color tint = Color.White;
                
                if (_triggered)
                { 
                    tint = Color.White * (1f - (fadeTimer / FadeDuration));
                }
                else
                {
                    tint = Color.White * (fadeTimer / FadeDuration);
                }

                anim.CurrentAnimation.Tint = tint;

                if(fadeTimer >= FadeDuration * 0.5f)
                    anim.CheckPlayerCollision = !_triggered;
            }

            if (_triggered && TriggerOnce)
                return;

            if (update || !TriggerOnPlayerCollission || (TriggerOnce == false && _triggered == true))
            {
                Timer += dt;

                while (Timer >= TriggerTime)
                {
                    _triggered = !_triggered;
                    Timer -= TriggerTime;
                    fadeTimer = 0;
                }
            }

            update = false;
        }
    }
}
